/*
	COMMON SERVER SIDE JAVASCRIPTS
*/

var mysql = require('mysql');

global.config = {
	host: "localhost",
	database: "gs3_e-forms",
	user: "root",
	password: "password"
};

global.conn = mysql.createConnection({
		host : 'localhost',
		user : 'root',
		password : 'password',
		database : 'gs3_e-forms'
});


global.updateItemInSQL = function(tblName, fieldName, fieldValue, keyField, keyValue, postFix){
	
	var strSQL = "UPDATE " + tblName + " SET " +  fieldName + " = " + conn.escape(fieldValue) + " WHERE " + keyField + " = " + conn.escape(keyValue) +  postFix

	console.log(strSQL);
	conn.query(strSQL);
}


global.insertRecord = function(tblName, fields, req){
	var createSQL = "INSERT INTO " + tblName + " ( ";
	
	for(var ctr=1;ctr<fields.length;ctr++){
		if(ctr<fields.length-1){
		createSQL += fields[ctr] + ", ";
		}else{
		createSQL += fields[ctr] + "";
		}
	}
	
	createSQL+=") VALUES (";
	
	for(var ctr=1;ctr<fields.length;ctr++){
		if(ctr<fields.length-1){
		createSQL += conn.escape(req.param(fields[ctr],null)) + ", ";
		}else{
		createSQL += conn.escape(req.param(fields[ctr],null));
		}
	}
	
	createSQL+=")";
	
	//console.log(createSQL);
	console.log("INSERTING RECORD...." + tblName);
	conn.query(createSQL);
	console.log("Done INSERTING RECORD..." + tblName);
}

global.updateRecord = function(tblName, fields, req){
	var updateSQL = "UPDATE " + tblName + " SET ";
	
	for(var ctr=1;ctr<fields.length;ctr++){
		if(ctr<fields.length-1){
		updateSQL += fields[ctr] + " = " + conn.escape(req.param(fields[ctr],null)) + ", ";
		}else{
		updateSQL +=  fields[ctr] + " = " + conn.escape(req.param(fields[ctr],null));
		}
	}
	
	updateSQL+=" WHERE ID = " + conn.escape(req.body.requestID) + "";
	
	console.log(updateSQL);
	console.log("UPDATING RECORD...." + tblName);
	conn.query(updateSQL);
	console.log("Done UPDATING RECORD..." + tblName);
}